<template>
    <div class="exam-container">
      <!-- 考试信息头部 -->
      <div class="exam-header">
        <h2>{{ examInfo.name }}</h2>
        <div class="exam-meta">
          <span>总分：{{ examInfo.totalScore }}分</span>
          <span>考试时长：{{ examInfo.timeLimit }}分钟</span>
          <span>剩余时间：{{ formattedTime }}</span>
        </div>
      </div>
  
      <!-- 答题主体区域 -->
      <div class="exam-body">
        <!-- 左侧题目导航 -->
        <div class="question-nav">
          <div  v-for="(q, index) in questions" :key="q.id" class="nav-item"
            :class="{ 
              'current': currentIndex === index,
              'answered': isAnswered(q.id),
              'marked': isMarked(q.id)
            }"
            @click="goToQuestion(index)"
          >{{ index + 1 }}</div>
        </div>
  
        <!-- 右侧题目内容 -->
        <div class="question-content">
          <!-- 题目展示区 -->
          <div class="question-area">
            <div class="question-title">
              <span class="question-type">{{ getQuestionTypeText(currentQuestion.type) }}</span>
              <span class="question-score">{{ getQuestionScore(currentQuestion.id) }}分</span>
              <h3>{{ currentQuestion.content }}</h3>
            </div>
            <!-- 单选题 -->
            <div v-if="currentQuestion.type === 'single'" class="options">
              <el-radio-group v-model="answers[currentQuestion.id]">
                <el-radio  v-for="option in currentQuestion.options"  :key="option.id" :label="option.id" class="option-item">
                  {{ option.text }}
                </el-radio>
              </el-radio-group>
            </div>
            <!-- 多选题 -->
            <div v-if="currentQuestion.type === 'multiple'" class="options">
              <el-checkbox-group v-model="answers[currentQuestion.id]">
                <el-checkbox  v-for="option in currentQuestion.options" :key="option.id" :label="option.id" class="option-item">
                  {{ option.text }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 判断题 -->
            <div v-if="currentQuestion.type === 'judgment'" class="options">
              <el-radio-group v-model="answers[currentQuestion.id]">
                <el-radio label="true" class="option-item">正确</el-radio>
                <el-radio label="false" class="option-item">错误</el-radio>
              </el-radio-group>
            </div>
  
            <!-- 标记按钮 -->
            <div class="action-buttons">
              <el-button  type="warning" size="small"  @click="toggleMark(currentQuestion.id)" :icon="isMarked(currentQuestion.id) ? 'el-icon-star-on' : 'el-icon-star-off'">
                {{ isMarked(currentQuestion.id) ? '取消标记' : '标记本题' }}
              </el-button>
            </div>
          </div>
  
          <!-- 题目切换按钮 -->
          <div class="question-switch">
            <el-button type="primary" :disabled="currentIndex === 0" @click="prevQuestion">上一题</el-button>
            <el-button  v-if="currentIndex < questions.length - 1" type="primary"  @click="nextQuestion">下一题</el-button>
            <el-button v-else type="success" @click="submitExam">提交试卷</el-button>
          </div>
        </div>
      </div>
  
      <!-- 提交确认对话框 -->
      <el-dialog title="确认提交" :visible.sync="submitDialogVisible" width="30%">
        <span>您确定要提交试卷吗？提交后不可修改！</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSubmit">确定提交</el-button>
        </span>
      </el-dialog>
    </div>
  </template>

<script>
import { getExamDetail, getQuestionsByExam, submitAnswers, createExamRecord } from '@/api/study-ask'

export default {
  name: 'ExamPaper',
  data() {
    return {
      examId: null,
      examInfo: {
        name: '',
        description: '',
        total_score: 100,
        time_limit: 120,
        start_time: null,
        end_time: null
      },
      questions: [],
      currentIndex: 0,
      answers: {},
      markedQuestions: [],
      remainingTime: 0,
      timer: null,
      submitDialogVisible: false,
      recordId: null
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentIndex] || {}
    },
    formattedTime() {
      const minutes = Math.floor(this.remainingTime / 60)
      const seconds = this.remainingTime % 60
      return `${minutes}分${seconds}秒`
    }
  },
  created() {
    this.examId = this.$route.params.id
    this.loadExamData()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    async loadExamData() {
      try {
        //获取考试信息
        const examRes = await getExamDetail(this.examId)
        this.examInfo = examRes.data
        //获取题目列表
        const questionRes = await getQuestionsByExam(this.examId)
        this.questions = questionRes.data.map(q => {
          return {
            ...q,
            options: q.options || []
          }
        }) 
        // 初始化答题记录
        this.initAnswers()
        // 开始计时
        this.startTimer()
        // 创建考试记录
        this.createExamRecord()
      } catch (error) {
        this.$message.error('加载考试数据失败: ' + error.message)
      }
    },
    initAnswers() {
      this.questions.forEach(q => {
        this.$set(this.answers, q.id, q.type === 'multiple' ? [] : '')
      })
    },
    startTimer() {
      // 计算剩余时间（秒）
      /*
      const totalSeconds = this.examInfo.timeLimit * 60
      const startTime = new Date(this.examInfo.startTime).getTime()
      const now = new Date().getTime()
      const elapsedSeconds = Math.floor((now - startTime) / 1000)
      this.remainingTime = Math.max(0, totalSeconds - elapsedSeconds)
      this.timer = setInterval(() => {
        if (this.remainingTime <= 0) {
          clearInterval(this.timer)
          this.timeoutSubmit()
        } else {
          this.remainingTime--
        }
      }, 1000)
      */
    },
    async createExamRecord() {
      try {
        const res = await createExamRecord({
          examId: parseInt(this.examId),
          userId: this.$store.state.user.id,
          startTime: new Date().toISOString(),
          status: 'in_progress'
        })
        this.recordId = res.data.id
      } catch (error) {
        this.$message.error('创建考试记录失败: ' + error.message)
      }
    },
    goToQuestion(index) {
      this.currentIndex = index
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
      }
    },
    nextQuestion() {
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++
      }
    },
    isAnswered(questionId) {
      const answer = this.answers[questionId]
      return Array.isArray(answer) ? answer.length > 0 : answer !== ''
    },
    toggleMark(questionId) {
      const index = this.markedQuestions.indexOf(questionId)
      if (index === -1) {
        this.markedQuestions.push(questionId)
      } else {
        this.markedQuestions.splice(index, 1)
      }
    },
    isMarked(questionId) {
      return this.markedQuestions.includes(questionId)
    },
    getQuestionTypeText(type) {
      const types = {
        single: '单选题',
        multiple: '多选题',
        judgment: '判断题'
      }
      return types[type] || type
    },
    getQuestionScore(questionId) {
      const question = this.questions.find(q => q.id === questionId)
      return question ? question.score : 0
    },
    submitExam() {
      this.submitDialogVisible = true
    },
    async confirmSubmit() {
      try {
        //保存用户答案
        const answerRecords = Object.keys(this.answers).map(questionId => {
          return {
            question_id: questionId,
            answer: JSON.stringify(this.answers[questionId])
          }
        })
        // 提交考试
        await submitAnswers({
          id: this.recordId,
          answers: answerRecords,
          submit_time: new Date().toISOString(),
          status: 'submitted'
        })
        this.$message.success('试卷提交成功！')
        //this.$router.push({ name: 'ExamResult', params: { recordId: this.recordId } })
        this.$router.push(`/study/ask/result/${this.recordId}`)
      } catch (error) {
        this.$message.error('提交失败: ' + error.message)
      } finally {
        this.submitDialogVisible = false
      }
    },
    timeoutSubmit() {
      this.$confirm('考试时间已结束，系统将自动提交您的试卷', '考试结束', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        this.confirmSubmit()
      })
    }
  }
}
</script>
<style scoped>
.exam-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: #f5f5f5;
}

.exam-header {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.exam-header h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.exam-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
}

.exam-body {
  display: flex;
  height: calc(100vh - 180px);
}

.question-nav {
  width: 60px;
  background-color: #fff;
  margin-right: 20px;
  border-radius: 4px;
  padding: 10px 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.nav-item {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin: 5px auto;
  border-radius: 50%;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item:hover {
  background-color: #e6f7ff;
}

.nav-item.current {
  background-color: #409EFF;
  color: white;
}

.nav-item.answered {
  background-color: #67C23A;
  color: white;
}

.nav-item.marked {
  background-color: #E6A23C;
  color: white;
}

.question-content {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.question-area {
  flex: 1;
  overflow-y: auto;
}

.question-title {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.question-type {
  display: inline-block;
  padding: 2px 8px;
  background-color: #409EFF;
  color: white;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 10px;
}

.question-score {
  color: #E6A23C;
  font-weight: bold;
}

.options {
  margin: 20px 0;
}

.option-item {
  display: block;
  margin: 10px 0;
  padding: 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.option-item:hover {
  background-color: #f5f5f5;
}

.action-buttons {
  margin: 20px 0;
}

.question-switch {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
</style>